import { toJS } from 'mobx';

import Exception403 from '@/components/exception/403';

import { store, useStore } from '@/store';

/**
 * 权限检查函数
 */
export const checkPermission = (
  authKey?: RouteData['authority'],
  permissions = store.permissions
): boolean => {
  // 超级管理员有所有权限
  if (store.role.includes(import.meta.env.VITE_SUPER_ADMIN)) {
    return true;
  }

  if (typeof authKey === 'undefined' || authKey === null || authKey === '' || authKey === '*') {
    return true;
  }

  if (Array.isArray(authKey)) {
    return authKey.some((key) => permissions.includes(key));
  }

  if (typeof authKey === 'string') {
    return store.permissions.includes(authKey);
  }

  return false;
};

/**
 * 权限检查 hook
 */
export const usePermission = () => {
  const store = useStore();
  const permissions = toJS(store.permissions);

  const check = (authKey?: RouteData['authority']) => {
    return checkPermission(authKey, permissions as string[]);
  };

  const isLogin = () => {
    return store.isLogin;
  };

  return {
    check,
    isLogin
  };
};

/**
 * 权限检查高阶组件
 */
export const withPermission = (authKey?: RouteData['authority']) => {
  return (WrappedComponent: React.ComponentType) => {
    const permission = usePermission();

    const render = () => {
      if (permission.check(authKey)) {
        return <WrappedComponent />;
      }

      return <Exception403 />;
    };

    return render;
  };
};
